import { Injectable } from '@nestjs/common';
import { CartsEntity, OrderEntity, OrderGoodEntity } from '../entities';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { ORDER_STATUS } from '../contance';
import { CreateOrderDto } from '../dto/create_order.dto';
import { User } from '@/modules/User/types';
import { UserService } from '@/modules/User/service';
import { OrderListDto } from '../dto/order_list.dto';
import { CommonService } from '@/modules/core/base/common.service';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(CartsEntity)
    private readonly cartsRepository: Repository<CartsEntity>,
    @InjectRepository(OrderEntity)
    private readonly orderRepository: Repository<OrderEntity>,
    @InjectRepository(OrderGoodEntity)
    private readonly orderGoodRepository: Repository<OrderGoodEntity>,
    private readonly commonService: CommonService,
    private readonly userService: UserService,
  ) {}
  async create(user: any, body: CreateOrderDto) {
    const order = this.orderRepository.create();
    const curUser = await this.userService.detail(user.userId);

    // 1. 获取当前用户的购物车信息
    const carts = await this.cartsRepository.find({
      where: {
        user: {
          id: user.userId,
        },
        is_select: true,
      },
      relations: ['good'],
    });
    if (carts.length === 0) {
      return {
        message: '当前购物车没有选中的商品',
        statusCode: 500,
      };
    }

    if (body.status === ORDER_STATUS.no_pay) {
      order.expire_time = new Date(Date.now() + 3600 * 1000 * 2);
    }
    order.status = body.status;
    order.user = curUser;
    order.total_price = body.total_price;
    const res = await order.save();
    // 需要将当前用户对应的carts的商品信息全部取出存入到order_goods表中

    // 2. 将购物车信息存入到order_goods表中
    for (let i = 0; i < carts.length; i++) {
      const cart = carts[i];
      const orderGood = this.orderGoodRepository.create();
      orderGood.good = cart.good;
      orderGood.num = cart.num;
      orderGood.order = order;
      await orderGood.save();
    }
    // 3. 将购物车信息删除
    await this.cartsRepository.remove(carts);

    return res;
  }
  async list(user: User, body: OrderListDto) {
    const qb = this.orderRepository.createQueryBuilder('order');
    const delQb = this.orderRepository.createQueryBuilder('order');
    qb.where('order.user = :user', {
      user: user.userId,
    });
    // 查询订单信息需要将过期的订单删除
    await delQb
      .where('order.expire_time < :now', {
        now: new Date(),
      })
      .andWhere('order.status = :status', {
        status: ORDER_STATUS.no_pay,
      })
      .delete()
      .execute();
    // 查询订单信息
    if (body.status) {
      qb.andWhere('order.status = :status', {
        status: body.status,
      });
    }
    qb.leftJoinAndSelect('order.orderGood', 'orderGood');
    qb.leftJoinAndSelect('orderGood.good', 'good');
    qb.leftJoinAndSelect('good.media', 'media');
    qb.orderBy('order.createdAt', 'DESC');
    const orders = await qb.getMany();
    return this.commonService.pagination(orders, body);
  }
  // 修改订单
  async update(user: User, id: string, body: CreateOrderDto) {
    const order = await this.orderRepository.findOne({
      where: {
        id: id,
        user: {
          id: user.userId,
        },
      },
    });
    if (!order) {
      return {
        message: '订单不存在',
        statusCode: 500,
      };
    }
    order.status = body.status;
    if (body.status !== ORDER_STATUS.no_pay) {
      order.expire_time = null;
    }
    if (Number(body.total_price) > 0) order.total_price = body.total_price;

    await order.save();
    return {
      message: '修改订单成功',
      statusCode: 200,
    };
  }
}
